package cn.initcap.bio.tcp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于TCP协议的Socket通信，实现用户登录
 * 服务端
 *
 * @author initcap
 * @date Created in 2018/6/7 PM10:10.
 */
public class Server {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //1.创建一个服务端Socket，即ServerSocket,指定绑定的端口
            serverSocket = new ServerSocket(8888);
            System.out.println("***服务端启动，等待客户端连接***");
            Socket socket = null;
            //记录客户端的数量
            int count = 0;
            //循环监听等待客户端的连接
            int j = 0;
            while (true) {
                j++;
                if (j == Integer.MAX_VALUE) {
                    break;
                }
                //调用accept()方法开始监听，等待客户端的连接
                socket = serverSocket.accept();
                //创建一个新的线程
                ServerThread serverThread = new ServerThread(socket);
                //启动线程
                serverThread.start();
                count++;
                System.out.println("客户端数量：" + count);
                InetAddress address = socket.getInetAddress();
                System.out.println("客户端的IP:" + address.getHostAddress());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
